<template>
  <el-button @click="downexcel" size="small" class="mr-10">{{optionBtn.btnText}}</el-button>
</template>

<script>
import downloadJson from './downloadJson.js'

export default {
  props: ['option', 'type'],
  name: 'download',
  watch: {
    type () {
      this.optionBtn = downloadJson.data[this.type]
    }
  },
  data () {
    return {
      httpData: '/',
      optionBtn: null
    }
  },
  created () {
    this.optionBtn = downloadJson.data[this.type]
  },
  methods: {
    // 导出excel文件
    downexcel () {
      let dataOption = []
      for (let i in this.option) {
        dataOption.push(i + '=' + this.option[i])
      }
      let request = `${this.$BASE_URL}/admin/${downloadJson.data[this.type].url }` + (dataOption.length ? '?' + dataOption.join('&') : '')
      this.$http({
        method: 'get',
        // url: this.httpData + '/admin/materiel/export?phone=' + this.editForm.phone,
        url: request,
        responseType: 'arraybuffer'
      })
        .then(
          function (response) {
            // let filename = this.editForm.phone + '物料（明细）.xlsx'
            this.fileDownload(response.data, downloadJson.data[this.type].filename)
          }.bind(this)
        )
        .catch(
          function (error) {
            alert('网络请求出错')
          }
        )
    },
    fileDownload (data, fileName) {
      let blob = new Blob([data], {
        type: 'application/octet-stream'
      })
      let filename = fileName || 'filename.xls'
      if (typeof window.navigator.msSaveBlob !== 'undefined') {
        window.navigator.msSaveBlob(blob, filename)
      } else {
        let blobURL = window.URL.createObjectURL(blob)
        let tempLink = document.createElement('a')
        tempLink.style.display = 'none'
        tempLink.href = blobURL
        tempLink.setAttribute('download', filename)
        if (typeof tempLink.download === 'undefined') {
          tempLink.setAttribute('target', '_blank')
        }
        document.body.appendChild(tempLink)
        tempLink.click()
        document.body.removeChild(tempLink)
        window.URL.revokeObjectURL(blobURL)
      }
    }
  }
}
</script>

<style scoped>

</style>
